package com.hz.foodstalls.controller;

import com.github.abel533.echarts.Title;
import com.hz.foodstalls.model.WechatInfo;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import com.hz.foodstalls.interceptor.AdminInterceptor;
import com.hz.foodstalls.model.WechatMenu;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;

import javax.mail.Flags;
import java.util.*;

/**
 * WechatMenuController, Generated by Robot on 2017-8-2 10:04:31.
 */
@Before(AdminInterceptor.class)
@ControllerBind(controllerKey = "/wechatmenu", viewPath = "/WEB-INF/views/wechatmenu/")
public class WechatMenuController extends BaseController {

    private final String MODULE_NAME = "/wechatmenu";

    public void index() {
        String id = getPara("id");
        String errcode = getPara("errcode");
        String menuName = getPara("menuName");
        if(menuName == null){
            Page<WechatMenu> page = WechatMenu.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10), id);
            pid(page);
            setAttr("page", page);
        }else{
            Page<WechatMenu> page = WechatMenu.dao.page1(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10), id,menuName);
            pid(page);
            setAttr("page", page);
        }

        setAttr("id",id);
        if(errcode!="0") {
            setAttr("errcode", getPara("errcode"));
        }
        render("index.html");
    }
    public void pid(Page<WechatMenu> page){
        List<WechatMenu> wlist = page.getList();
        Map<Integer,String> map = new HashMap<>();
        for(WechatMenu wechatMenu : wlist){
            if(wechatMenu.getPid() == 0){
                map.put(0,"/");
                continue;
            }
            map.put(wechatMenu.getPid(),WechatMenu.dao.getPNameByid(wechatMenu.getPid()));
        }
        setAttr("WechatMenuMap",map);
    }

    public void save() {
        WechatMenu model = getModel(WechatMenu.class, "");
        boolean isSave = model.getId() == null;

        if (WechatMenu.dao.saveOrUpdate(model, isSave))
            redirect(MODULE_NAME+"?id="+model.getWechatInfoId());
        else
            renderError(501);
    }

    public void edit() {

        int wechat_info_id=Integer.parseInt(getPara("wxid"));
        WechatMenu wechatMenu = WechatMenu.dao.findById(getParaToInt("id", 0));
        if (wechatMenu == null)
            wechatMenu = new WechatMenu();
        wechatMenu.put("wechat_info_id",wechat_info_id);

        List<WechatMenu> parent = WechatMenu.dao.findPId(wechat_info_id,getParaToInt("id",0));
        setAttr("parent",parent);

        setAttr("wechatMenu", wechatMenu);
        render("edit.html");
    }

    public void delete() {
        String ids = StringUtils.join(getParaValues("ids"), ",");
        int ret = WechatMenu.dao.batchDelete(ids);
        if (ret > 0) {
            ajaxJsonSuccessMessage("删除成功!");
        } else {
            ajaxJsonErrorMessage("删除失败！");
        }
    }

    public void create(){
        int wechat_info_id=Integer.parseInt(getPara("wxid"));
        WechatInfo wechatInfo = WechatInfo.dao.findById(wechat_info_id);
        String appid = wechatInfo.getAppid();
        ApiConfigKit.setThreadLocalAppId(appid);
        MenuApi.deleteMenu();
        List<WechatMenu> wechatMenuList = WechatMenu.dao.findAllWechatMenu(wechat_info_id);
        JSONObject param = new JSONObject();
        //查找所有准父节点
        List<WechatMenu> parentMenu = new ArrayList<WechatMenu>();
        for (WechatMenu menuPList : wechatMenuList){
            if (menuPList.getPid()==0) {
                parentMenu.add(menuPList);
            }
        }
        JSONObject[] button = new JSONObject[parentMenu.size()];
        for (int i = 0; i < parentMenu.size(); i++) {
            WechatMenu menu = (WechatMenu) parentMenu.get(i);
            button[i] = new JSONObject();
            List<WechatMenu> childMenu = new ArrayList<WechatMenu>();
            for (WechatMenu menuCList : wechatMenuList) {
                if (menuCList.getPid() == menu.getId()) {
                    childMenu.add(menuCList);
                }
            }
            setMenu(button[i], menu, childMenu);

        }

        param.accumulate("button", button);
        ApiResult apiResult = MenuApi.createMenu(param.toString());
        ApiConfigKit.removeThreadLocalAppId();
        if(apiResult.get("errmsg").equals("ok")) {
            redirect(MODULE_NAME + "?id=" + wechat_info_id);
        }else{
            redirect(MODULE_NAME + "?id=" + wechat_info_id+"&errcode="+apiResult.get("errcode"));
        }
    }
    public void setMenu(JSONObject jsonObject, WechatMenu menu,List<WechatMenu> childMenu) {
        jsonObject.accumulate("name", menu.getTitle());
        if (menu.getPid() == 0 && childMenu.size() == 0 || menu.getPid() !=0) {
            jsonObject.accumulate("type", menu.getType());
            if(menu.getType().equals("click")){
                jsonObject.accumulate("key",menu.getKey());
            }else {
                if ((menu.getLinkurl() != null) && (!menu.getLinkurl().equals(""))) {
                    if(menu.getLinkurl().startsWith("http://")){
                        jsonObject.accumulate("url",menu.getLinkurl());
                    }else{
                        jsonObject.accumulate("url","http://"+menu.getLinkurl());
                    }
                }else {
                    jsonObject.accumulate("url", "");
                }
            }

        }else if (menu.getPid() == 0 && childMenu.size() != 0) {
            JSONObject[] sub_button = new JSONObject[childMenu.size()];
            byte index = 0;
            for (Iterator it = childMenu.iterator(); it.hasNext();) {
                WechatMenu child = (WechatMenu) it.next();
                sub_button[index] = new JSONObject();
                setMenu(sub_button[index], child,null);
                index = (byte) (index + 1);
            }
            jsonObject.accumulate("sub_button", sub_button);
        }
    }
}
